package com.tiger.communal.service.impl;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

import com.tiger.common.constant.UserConstants;
import com.tiger.common.core.domain.AjaxResult;
import com.tiger.common.core.domain.entity.SysUser;
import com.tiger.common.core.redis.RedisCache;
import com.tiger.common.exception.CustomException;
import com.tiger.common.utils.Code;
import com.tiger.common.utils.DateUtils;
import com.tiger.common.utils.SecurityUtils;
import com.tiger.common.utils.StringUtils;
import com.tiger.communal.domain.TenantUnit;
import com.tiger.communal.domain.TenantUnitEnclosure;
import com.tiger.communal.domain.TenantUnitLinkman;
import com.tiger.communal.mapper.TenantUnitEnclosureMapper;
import com.tiger.communal.mapper.TenantUnitLinkmanMapper;
import com.tiger.communal.mapper.TenantUnitMapper;
import com.tiger.communal.service.ITenantUnitService;
import com.tiger.system.mapper.SysUserMapper;
import com.tiger.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 【承租单位管理】Service业务层处理
 *
 * @author standard
 * @date 2022-09-21
 */
@Service
public class TenantUnitServiceImpl implements ITenantUnitService {
    @Autowired
    private TenantUnitMapper tenantUnitMapper;
    @Autowired
    private TenantUnitLinkmanMapper linkmanMapper;
    @Autowired
    private TenantUnitEnclosureMapper enclosureMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询【承租单位管理】
     *
     * @param id 【承租单位管理】主键
     * @return 【承租单位管理】
     */
    @Override
    public TenantUnit selectTenantUnitById(Long id) {
        TenantUnit tenantUnit = tenantUnitMapper.selectTenantUnitById(id);
        //联系人
        TenantUnitLinkman linkman = new TenantUnitLinkman();
        linkman.setTenantUnitId(id);
        List<TenantUnitLinkman> tenantUnitLinkmanList = linkmanMapper.selectTenantUnitLinkmanList(linkman);
        if (tenantUnitLinkmanList != null && tenantUnitLinkmanList.size() > 0){
            tenantUnit.getLinkmanList().addAll(tenantUnitLinkmanList);
        }
        //附件
        TenantUnitEnclosure enclosure = new TenantUnitEnclosure();
        enclosure.setTenantUnitId(id);
        List<TenantUnitEnclosure> tenantUnitEnclosureList = enclosureMapper.selectTenantUnitEnclosureList(enclosure);
        if (tenantUnitEnclosureList != null && tenantUnitEnclosureList.size() > 0){
            tenantUnit.getEnclosureList().addAll(tenantUnitEnclosureList);
        }

        return tenantUnit;
    }

    /**
     * 查询【承租单位管理】列表
     *
     * @param tenantUnit 【承租单位管理】
     * @return 【承租单位管理】
     */
    @Override
    public List<TenantUnit> selectTenantUnitList(TenantUnit tenantUnit) {
        return tenantUnitMapper.selectTenantUnitList(tenantUnit);
    }

    /**
     * 新增【承租单位管理】
     *
     * @param tenantUnit 【承租单位管理】
     * @return 结果
     */
    @Override
    public int insertTenantUnit(TenantUnit tenantUnit) {
        int code = redisCache.getCacheObjectCode(LocalDate.now().format(Code.fmt) + "cz");
        addCode(code);
        tenantUnit.setTenantUnitNo(String.format("%s%s%04d", "CZ",LocalDate.now().format(Code.fmt), code));
        tenantUnit.setCreatedAt(DateUtils.getNowDate());
        tenantUnit.setIsDeleted(0L);
        int i = tenantUnitMapper.insertTenantUnit(tenantUnit);
        change(tenantUnit);

        //创建的承租单位，手机号作为账号，密码默认123456
        SysUser user = new SysUser();
        user.setDeptId(tenantUnit.getCompanyId());
        user.setNickName(tenantUnit.getContactPhone());
        user.setUserName(tenantUnit.getContactPhone());
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            throw new CustomException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        try {
            userService.insertUser(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 修改【承租单位管理】
     *
     * @param tenantUnit 【承租单位管理】
     * @return 结果
     */
    @Override
    public int updateTenantUnit(TenantUnit tenantUnit) {
        change(tenantUnit);
        tenantUnit.setCreatedAt(DateUtils.getNowDate());
        return tenantUnitMapper.updateTenantUnit(tenantUnit);
    }

    /**
     * 批量删除【承租单位管理】
     *
     * @param ids 需要删除的【承租单位管理】主键
     * @return 结果
     */
    @Override
    public int deleteTenantUnitByIds(Long[] ids) {
        return tenantUnitMapper.deleteTenantUnitByIds(ids);
    }

    /**
     * 删除【承租单位管理】信息
     *
     * @param id 【承租单位管理】主键
     * @return 结果
     */
    @Override
    public int deleteTenantUnitById(Long id) {
        return tenantUnitMapper.deleteTenantUnitById(id);
    }

    /**
     * 生成编码
     */
    private synchronized void addCode(int code) {
        redisCache.setCacheObject(LocalDate.now().format(Code.fmt) + "cz", code + 1);
    }

    private void change(TenantUnit tenantUnit){
        //联系人
        linkmanMapper.deleteTenantUnitLinkmanByTenantUnitId(tenantUnit.getId());
        if (StringUtils.isNotEmpty(tenantUnit.getLinkmanList())){
            tenantUnit.getLinkmanList().forEach(item -> {
                item.setTenantUnitId(tenantUnit.getId());
                linkmanMapper.insertTenantUnitLinkman(item);
            });
        }

        //附件
        enclosureMapper.deleteTenantUnitEnclosureByTenantUnitId(tenantUnit.getId());
        if (StringUtils.isNotEmpty(tenantUnit.getEnclosureList())){
            tenantUnit.getEnclosureList().forEach(tenantUnitEnclosure -> {
                tenantUnitEnclosure.setTenantUnitId(tenantUnit.getId());
                tenantUnitEnclosure.setCreatedAt(DateUtils.getNowDate());
                tenantUnitEnclosure.setState("1");
                enclosureMapper.insertTenantUnitEnclosure(tenantUnitEnclosure);
            });
        }
    }


}
